<template>
	<view>
		<u-popup
			v-model="value"
			mode="bottom"
			:mask="true"
			:popup="false"
			:closeable="true"
			:safe-area-inset-bottom="true"
			:z-index="zIndex"
			:maskCloseAble="maskCloseAble"
			:borderRadius="20"
			close-icon-color="#ffffff"
			@close="close"
		>
			<u-cell-group>
				<u-cell-item :arrow="false">
					<view class="m-pay-item__title">
						<view>请选择支付方式</view>
						<view>
							支付金额：
							<text class="m-pay-amuont">￥{{ order.amount_real }}</text>
						</view>
					</view>
				</u-cell-item>

				<u-cell-item :arrow="false" v-for="item in lists" :key="item.id" @click="switchPayment(item)">
					<label class="m-pay-item u-flex" v-if="item.type.indexOf('balance') > -1">
						<image :src="item.cover" mode="aspectFill" class="m-pay-logo" :lazy-load="true"></image>

						<view v-if="Number(order.amount_real) > Number(balance)" class="u-flex u-flex-1">
							<view class="u-text-left">
								<view class="u-content-color m-font-bold">{{ item.name }}</view>
								<view class="u-tips-color u-font-xs">可用余额 {{ balance.toFixed(2) }} 元，余额不足</view>
							</view>
							<view class="m-recharge">去充值</view>
						</view>

						<view v-else class="u-flex u-flex-1">
							<view class="u-text-left">
								<view class="u-content-color m-font-bold">{{ item.name }}</view>
								<view class="u-tips-color u-font-xs">（可用余额 {{ balance.toFixed(2) }} 元）</view>
							</view>
						</view>
					</label>

					<label class="m-pay-item" v-else-if="item.type.indexOf('wechat') > -1">
						<image :src="item.cover" mode="aspectFill" class="m-pay-logo" :lazy-load="true"></image>
						<text>{{ item.name }}</text>
					</label>

					<label class="m-pay-item" v-else-if="item.type.indexOf('alipay') > -1">
						<image :src="item.cover" mode="aspectFill" class="m-pay-logo" :lazy-load="true"></image>
						<text>{{ item.name }}</text>
					</label>

					<label class="m-pay-item" v-else-if="item.type.indexOf('voucher') > -1">
						<image :src="item.cover" mode="aspectFill" class="m-pay-logo" :lazy-load="true"></image>

						<view class="u-text-left">
							<view class="u-content-color m-font-bold">{{ item.name }}</view>
							<view class="u-tips-color u-font-xs">需要上传支付凭证单据图片</view>
						</view>
					</label>
					<view class="u-p-20"></view>

					<u-icon
						v-if="(item.type.indexOf('balance') > -1 && Number(order.amount_real) <= Number(balance)) || item.type.indexOf('balance') === -1"
						slot="right-icon"
						name="arrow-right"
						color="#969799"
						size="22"
					></u-icon>
				</u-cell-item>
			</u-cell-group>
		</u-popup>

		<u-popup v-model="voucherShow" :maskCloseAble="false" :closeable="true" mode="center" borderRadius="14">
			<view class="u-p-40">
				<view class="u-text-center m-font-bold">请上传支付凭证单据截图</view>
				<view class="u-text-center u-p-t-30 u-p-b-30 u-relative">
					<u-upload
						ref="uUpload"
						:width="500"
						:height="500"
						:maxCount="1"
						:multiple="false"
						:deletable="false"
						:autoUpload="false"
						:previewFullImage="false"
						@on-choose-complete="voucherImageCount = $refs.uUpload.lists.length"
					></u-upload>
					<view class="m-upload-icon" v-show="voucherImageCount > 0">
						<u-icon name="close-circle-fill" @click="clearVoucherImage" color="#ff0000" size="50"></u-icon>
					</view>
				</view>
				<u-button type="error" shape="circle" shadow @click="uploadVoucherImage">确 认 提 交</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
/**
 * select-payment 平台支付组件
 * @property {Object} order 待支付订单对象
 * @property {Number} balance 当前用户可用余额
 * @property {String} z-index 弹出时的z-index值（默认1075）
 * @property {String} city-value 默认选中的地区, 以英文空格分开
 * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker（默认true）
 */
export default {
	name: 'm-select-payment',
	props: {
		// 控制显示
		value: {
			type: Boolean,
			default: false
		},
		// 当前订单数据
		order: {
			type: Object,
			default() {
				return {};
			}
		},
		// 用户可用余额
		balance: {
			type: Number,
			default: 0.0
		},
		// 是否允许遮罩关闭
		maskCloseAble: {
			type: Boolean,
			default: true
		},
		// 弹出的zIndex值
		zIndex: {
			type: [String, Number],
			default: 0
		}
	},
	data() {
		return {
			lists: [],
			payment: {},
			voucherShow: false,
			voucherImageCount: 0
		};
	},
	mounted() {
		this.$u.post('data/api.auth.order/channel', { order_no: this.order.order_no }).then(ret => {
			this.lists = ret.data;
		});
	},
	methods: {
		close() {
			this.$emit('input', false);
		},
		// 清理上传的图片
		clearVoucherImage() {
			this.$refs.uUpload.clear();
			this.voucherImageCount = this.$refs.uUpload.lists.length;
		},
		// 上传支付凭证图片
		uploadVoucherImage() {
			((that, file, reader) => {
				reader.readAsDataURL(file);
				reader.onload = function(evt) {
					that.$u.api.post('data/api.auth.center/image', { base64: evt.target.result }, true, false, true).then(ret => {
						if (ret.code > 0) {
							that.requestPayment({ payment_image: ret.data.url });
						} else {
							that.$u.message.toast(ret.info);
						}
					});
				};
			})(this, this.$refs.uUpload.lists[0].file, new FileReader());
		},
		// 选择支付方案
		switchPayment(payment) {
			let that = this;
			this.payment = payment;
			if (payment.type.indexOf('voucher') > -1) {
				this.voucherShow = true;
			} else if (payment.type.indexOf('balance') > -1) {
				this.requestPayment({});
			} else if (payment.type.indexOf('wechat_xcx') > -1 || payment.type.indexOf('wechat_gzh') > -1) {
				this.requestPayment({}, true).then(param => {
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: param.timeStamp,
						nonceStr: param.nonceStr,
						package: param.package,
						signType: param.signType,
						paySign: param.paySign,
						success: function(res) {
							that.close();
							this.$u.route({
								url: 'pages/order/show',
								type: 'redirect',
								params: {
									order: ret.data.order_no || ''
								}
							});
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
				});
			}
		},
		// 获取支付参数
		requestPayment(data, handle) {
			let that = this;
			return new Promise((resolve, reject) => {
				data.order_no = this.order.order_no;
				data.payment_code = this.payment.code;
				that.$u.api.post('data/api.auth.order/payment', data, true, false, true).then(ret => {
					if (ret.code > 0) {
						if (handle) return resolve(ret.data.param);
						if (ret.data.param.code > 0) {
							return that.$u.message.toast(ret.data.param.info).then(() => {
								this.close();
								this.$u.route({
									url: 'pages/order/show',
									type: 'redirect',
									params: {
										order: data.order_no || ''
									}
								});
							});
						}
					}
					that.close();
					return this.$u.message.toast(ret.info);
					return that.$u.message.alert(ret.info);
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.m-pay-item__title {
	width: 100%;
	height: 90rpx;
	display: flex;
	padding: 0 20rpx;
	font-size: 28rpx;
	box-sizing: border-box;
	align-items: center;
	justify-content: space-between;
}

.m-pay-amuont {
	color: #eb0909;
	font-weight: 500;
	font-size: 34rpx;
}

.m-pay-item {
	width: 100%;
	height: 80rpx;
	display: flex;
	padding: 0 20rpx;
	font-size: 28rpx;
	align-items: center;
	box-sizing: border-box;
}

.m-pay-logo {
	width: 80rpx;
	height: 80rpx;
	margin-right: 32rpx;
}

.m-radio {
	margin-left: auto;
	transform: scale(0.8);
	transform-origin: 100% center;
}

.m-btn-pay {
	width: 100%;
	padding: 68rpx 60rpx 50rpx;
	box-sizing: border-box;
}

.m-recharge {
	color: #fc872d;
	padding: 12rpx 0;
	margin-left: auto;
}

.m-upload-icon {
	top: 50rpx;
	right: 20rpx;
	position: absolute;
}
</style>
